package com.mdp.sms.ctrl;

import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.sms.Validator;
import com.mdp.sms.api.SmsService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
/**
 *短信验证码发送验证等
 ***/
@RestController("mdp.smsController")
@RequestMapping(value="/**/sms")
public class SmsController{
	
	static Log logger=LogFactory.getLog(SmsController.class);
	
	@Autowired
	private SmsService smsService;
	
	/**
	 * 发送短信验证码
	 */
	@RequestMapping(value="/sendSmsCode")
	public Result sendSmsCode(@RequestBody Map<String,Object> map){
		String moblie=(String) map.get("phoneno");
		if(StringUtils.isEmpty(moblie)){
			return Result.error("phoneno-required","手机号码不能为空");
		}
		if(Validator.checkMobileNumber(moblie)){ 
			String scene=(String) map.get("scene");
			Tips tips=new Tips("发送验证码成功");
			if(StringUtils.isEmpty(scene)) {
				tips=smsService.sendCommonValidCode(moblie);
			}else if("login".equals(scene)) {
				tips=smsService.sendLoginValidCode(moblie);
			}else if("register".equals(scene)) {
				tips=smsService.sendRegisterValidCode(moblie);
			}else  {
				tips=smsService.sendValidCode(moblie,scene);
			}
			Result.assertIsFalse(tips);
		} else{
			return Result.error("phoneno-format-err","手机号码格式不正确");
		}
		return Result.ok("发送验证码成功");
	}
	/**
	 * 发送短信验证码
	 */
	@RequestMapping(value="/validateSmsCode")
	public Result validSmsCode(@RequestBody Map<String,Object> map){
		Tips tips=new Tips("验证码验证成功");
		String moblie=(String) map.get("phoneno");
		String code=(String) map.get("code");
		if(StringUtils.isEmpty(moblie)){
			return Result.error("phoneno-required","手机号码不能为空");
		}
		if(StringUtils.isEmpty(code)){
			return Result.error("sms-code-required","短信验证码不能为空");
		}else if(code.length()<6){
			return Result.error("sms-code-length-must-six","短信验证码必须为6位数字");
		}
		if(tips.isOk()){
			if(Validator.checkMobileNumber(moblie)){
				String scene=(String) map.get("scene");
				if(StringUtils.isEmpty(scene)) {
					tips=smsService.validateSmsCode(moblie,code);
				}else {
					tips=smsService.validateSmsCode(moblie,code,scene);
				}
				
			}else{
				return Result.error("phoneno-format-err","手机号码格式不正确");
			}
		}
		return Result.ok("发送验证码成功");
	}
}